package com.cnb.telepathytalk.database;

import java.util.Locale;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class PictureIndexDbAdapter {
	private static final String DATABASE_NAME = "picture.db";
	private static final String DATABASE_TABLE = "picture";

	private static final String KEY_ID = "_id";
	private static final String KEY_INDEX = "code";
	private static final String KEY_ADDRESS = "address";

	private DatabaseHelper dbHelper;
	private SQLiteDatabase database;

	private static final int DATABASE_VERSION = 1;
	private final Context context;

	public PictureIndexDbAdapter(Context context) {
		this.context = context;
	}

	public synchronized PictureIndexDbAdapter open() {
		dbHelper = new DatabaseHelper(context);
		database = dbHelper.getWritableDatabase();

		return this;
	}

	public synchronized void close() {
		try {
			dbHelper.close();
		} catch (Exception e) {
		}
	}

	public long insert(int index, String address) {
		ContentValues values = new ContentValues();
		values.put(KEY_INDEX, index);
		values.put(KEY_ADDRESS, address);
		return database.insert(DATABASE_TABLE, null, values);
	}

	public String getAddress(int index) {
		try {
			Cursor cursor = database.query(true, DATABASE_TABLE, new String[] { KEY_ID, KEY_INDEX, KEY_ADDRESS }, KEY_INDEX + "=" + index, null,
					null, null, null, null);
			if (cursor != null) {
				cursor.moveToFirst();
			}
			return cursor.getString(2);
		} catch (Exception e) {
			return "";
		}
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		private static final String DATABASE_CREATE = String.format(Locale.getDefault(),
				"create table %s (%s integer primary key autoincrement, %s integer, %s text);", DATABASE_TABLE, KEY_ID, KEY_INDEX, KEY_ADDRESS);

		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			onCreate(db);
		}
	}
}